/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package net.sf.l2j.gameserver.templates.chars;

import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javolution.util.FastList;
import javolution.util.FastMap;
import net.sf.l2j.gameserver.datatables.HerbDropTable;
import net.sf.l2j.gameserver.model.L2DropCategory;
import net.sf.l2j.gameserver.model.L2DropData;
import net.sf.l2j.gameserver.model.L2MinionData;
import net.sf.l2j.gameserver.model.L2NpcAIData;
import net.sf.l2j.gameserver.model.L2Skill;
import net.sf.l2j.gameserver.model.actor.instance.L2XmassTreeInstance;
import net.sf.l2j.gameserver.model.base.ClassId;
import net.sf.l2j.gameserver.model.quest.Quest;
import net.sf.l2j.gameserver.templates.StatsSet;

/**
 * This class contains all generic data of a L2Spawn object.<BR>
 * <li>npcId, type, name, sex</li>
 * <li>rewardExp, rewardSp</li>
 * <li>aggroRange, factionId, factionRange</li>
 * <li>rhand, lhand</li>
 * <li>_drops</li>
 * <li>_minions</li>
 * <li>_teachInfo</li>
 * <li>_skills</li>
 * <li>_questsStart</li>
 */
public final class L2NpcTemplate extends L2CharTemplate
{
	protected static final Logger _log = Logger.getLogger(Quest.class.getName());

	public final int npcId;
    public final int idTemplate;
	public final String type;
	public final String name;
    public final boolean serverSideName;
    public final String title;
    public final boolean serverSideTitle;
	public final String sex;
	public final byte level;
	public final int rewardExp;
	public final int rewardSp;
	public final int aggroRange;
	public final int rhand;
	public final int lhand;
	public final int enchantEffect;
	public final int dropherbgroup;
    public Race race;
	public boolean cantBeChampionMonster; // used for champion option ; avoid to popup champion quest mob.
	
	// Skills AI
	public FastList<L2Skill> _buffSkills;
	public FastList<L2Skill> _negativeSkills;
	public FastList<L2Skill> _debuffSkills;
	public FastList<L2Skill> _atkSkills;
	public FastList<L2Skill> _rootSkills;
	public FastList<L2Skill> _stunSkills;
	public FastList<L2Skill> _sleepSkills;
	public FastList<L2Skill> _paralyzeSkills;
	public FastList<L2Skill> _fossilSkills;
	public FastList<L2Skill> _immobilizeSkills;
	public FastList<L2Skill> _healSkills;
	public FastList<L2Skill> _dotSkills;
	public FastList<L2Skill> _cotSkills;
	public FastList<L2Skill> _universalSkills;
	public FastList<L2Skill> _manaSkills;
	public FastList<L2Skill> _longRangeSkills;
	public FastList<L2Skill> _shortRangeSkills;
	public FastList<L2Skill> _generalSkills;
	public FastList<L2Skill> _suicideSkills;
	
	private L2NpcAIData _AIdataStatic = new L2NpcAIData();
	
	public static enum AIType
	{
		FIGHTER,
		ARCHER,
		BALANCED,
		MAGE,
		HEALER,
		CORPSE
	}
    
    public static enum Race 
	{ 
    	UNDEAD, 
    	MAGICCREATURE, 
    	BEAST, 
    	ANIMAL, 
    	PLANT, 
    	HUMANOID, 
    	SPIRIT, 
    	ANGEL, 
    	DEMON, 
    	DRAGON, 
    	GIANT, 
    	BUG, 
    	FAIRIE, 
    	HUMAN, 
    	ELVE, 
    	DARKELVE, 
    	ORC, 
    	DWARVE, 
    	OTHER, 
    	NONLIVING, 
    	SIEGEWEAPON, 
    	DEFENDINGARMY, 
    	MERCENARIE, 
    	UNKNOWN 
	}
	
	/** The table containing all Item that can be dropped by L2Npc using this L2NpcTemplate*/
	private FastList<L2DropCategory> _categories = null;
	
	/** The table containing all Minions that must be spawn with the L2Npc using this L2NpcTemplate*/
	private List<L2MinionData> _minions = null;
	
	private List<ClassId> _teachInfo;
	private Map<Integer, L2Skill> _skills;
	
	// contains a list of quests for each event type (questStart, questAttack, questKill, etc)
	private Map<Quest.QuestEventType, Quest[]> _questEvents;
	
	/**
	 * Constructor of L2Character.<BR><BR>
	 * @param set The StatsSet object to transfert data to the method
	 */
	public L2NpcTemplate(StatsSet set)
	{
		super(set);
		npcId = set.getInteger("npcId");
        idTemplate = set.getInteger("idTemplate");
		type = set.getString("type");
		name = set.getString("name");
        serverSideName = set.getBool("serverSideName");
        title = set.getString("title");
        
		if (title.equalsIgnoreCase("Quest Monster") || type.equalsIgnoreCase("L2Chest"))
			cantBeChampionMonster = true;
		else
			cantBeChampionMonster = false;
        
        serverSideTitle = set.getBool("serverSideTitle");
		sex = set.getString("sex");
		level = set.getByte("level");
		rewardExp = set.getInteger("rewardExp");
		rewardSp = set.getInteger("rewardSp");
		aggroRange = set.getInteger("aggroRange");
		rhand = set.getInteger("rhand");
		lhand = set.getInteger("lhand");
		enchantEffect = set.getInteger("enchant");
    	race = null;
		_teachInfo = null;
		
		int herbGroup = set.getInteger("dropHerbGroup");
		if (herbGroup > 0 && HerbDropTable.getInstance().getHerbDroplist(herbGroup) == null)
		{
			_log.warning("Missing Herb Drop Group for npcId: " + npcId);
			dropherbgroup = 0;
		}
		else
			dropherbgroup = herbGroup;
	}
	
    public void addTeachInfo(ClassId classId)
	{
		if (_teachInfo == null)
			_teachInfo = new FastList<ClassId>();
		
		_teachInfo.add(classId);
	}
	
	public ClassId[] getTeachInfo()
	{
		if (_teachInfo == null)
			return null;
		
		return _teachInfo.toArray(new ClassId[_teachInfo.size()]);
	}
    
	public boolean canTeach(ClassId classId)
	{
		if (_teachInfo == null)
			return false;
        
        // If the player is on a third class, fetch the class teacher information for its parent class.
		if (classId.level() == 3)
            return _teachInfo.contains(classId.getParent());
        
		return _teachInfo.contains(classId);
	}
	
	// add a drop to a given category.  If the category does not exist, create it.
    public void addDropData(L2DropData drop, int categoryType)
	{
	    if (!drop.isQuestDrop()) 
	    {
			if (_categories == null)
				_categories = new FastList<L2DropCategory>();
			
	    	// if the category doesn't already exist, create it first
	    	synchronized (_categories)
	    	{
	    		boolean catExists = false;
	    		for (L2DropCategory cat : _categories)
	    	    	// if the category exists, add the drop to this category.
	    			if (cat.getCategoryType() == categoryType)
	    			{
	    				cat.addDropData(drop, type.equalsIgnoreCase("L2RaidBoss") || type.equalsIgnoreCase("L2GrandBoss"));
	    				catExists = true;
	    				break;
	    			}
	    		// if the category doesn't exit, create it and add the drop
	    		if (!catExists)
	    		{
	    			L2DropCategory cat = new L2DropCategory(categoryType);
	    			cat.addDropData(drop, type.equalsIgnoreCase("L2RaidBoss") || type.equalsIgnoreCase("L2GrandBoss"));
	    			_categories.add(cat);
	    		}
	    	}
	    }
	}
    
    public void addRaidData(L2MinionData minion)
    {
		if (_minions == null)
			_minions = new FastList<L2MinionData>();
		
    	_minions.add(minion);
    }
	
	public void addSkill(L2Skill skill)
	{
		if (_skills == null)
			_skills = new FastMap<Integer, L2Skill>();
		
		if (!skill.isPassive())
		{
			if (skill.isSuicideAttack())
				addSuicideSkill(skill);
			else
			{
				addGeneralSkill(skill);
				switch(skill.getSkillType())
				{
					case BUFF:
						addBuffSkill(skill);
						break;
					case HEAL:
					case HOT:
					case HEAL_PERCENT:
					case HEAL_STATIC:
					case BALANCE_LIFE:
						addHealSkill(skill);
						break;
					case DEBUFF:
						addDebuffSkill(skill);
						addCOTSkill(skill);
						addRangeSkill(skill);
						break;
					case ROOT:
						addRootSkill(skill);
						addImmobilizeSkill(skill);
						addRangeSkill(skill);
						break;
					case SLEEP:
						addSleepSkill(skill);
						addImmobilizeSkill(skill);
						break;
					case STUN:
						addRootSkill(skill);
						addImmobilizeSkill(skill);
						addRangeSkill(skill);
						break;
					case PARALYZE:
						addParalyzeSkill(skill);
						addImmobilizeSkill(skill);
						addRangeSkill(skill);
						break;
					case PDAM:
					case MDAM:
					case BLOW:
					case DRAIN:
					case CHARGEDAM:
					case FATAL:
					case DEATHLINK:
					case MANADAM:
					case CPDAMPERCENT:
						addAtkSkill(skill);
						addUniversalSkill(skill);
						addRangeSkill(skill);
						break;
					case POISON:
					case DOT:
					case MDOT:
					case BLEED:
						addDOTSkill(skill);
						addRangeSkill(skill);
						break;
					case MUTE:
					case FEAR:
						addCOTSkill(skill);
						addRangeSkill(skill);
						break;
					case CANCEL:
					case NEGATE:
						addNegativeSkill(skill);
						addRangeSkill(skill);
						break;
					default :
						addUniversalSkill(skill);
						break;
				}
			}
		}
		_skills.put(skill.getId(), skill);
	}
	
	/**
	 * Return the list of all possible UNCATEGORIZED drops of this L2NpcTemplate.<BR><BR>
	 */
	public FastList<L2DropCategory> getDropData()
	{
		return _categories;
	}	

    /**
     * Return the list of all possible item drops of this L2NpcTemplate.<BR>
     * (ie full drops and part drops, mats, miscellaneous & UNCATEGORIZED)<BR><BR>
     */
    public List<L2DropData> getAllDropData()
    {
		if (_categories == null)
			return null;
		
        List<L2DropData> lst = new FastList<L2DropData>();
        for (L2DropCategory tmp:_categories)
        	lst.addAll(tmp.getAllDrops());
        
        return lst;
    }
    
    /**
     * Empty all possible drops of this L2NpcTemplate.<BR><BR>
     */
    public synchronized void clearAllDropData()
    {
		if (_categories == null)
			return;
		
		while (!_categories.isEmpty())
    	{
    		_categories.getFirst().clearAllDrops();
    		_categories.removeFirst();
    	}
        _categories.clear();
    }

	/**
	 * Return the list of all Minions that must be spawn with the L2Npc using this L2NpcTemplate.<BR><BR>
	 */
	public List<L2MinionData> getMinionData()
	{
		return _minions;
	}

    public Map<Integer, L2Skill> getSkills()
	{
		return _skills;
	}
	    
    public void addQuestEvent(Quest.QuestEventType EventType, Quest q)
    {
    	if (_questEvents == null) 
    		_questEvents = new FastMap<Quest.QuestEventType, Quest[]>();
    		
		if (_questEvents.get(EventType) == null)
			_questEvents.put(EventType, new Quest[]{q});
		else 
		{
			Quest[] _quests = _questEvents.get(EventType);
			int len = _quests.length;
			
			// if only one registration per npc is allowed for this event type
			// then only register this NPC if not already registered for the specified event.
			// if a quest allows multiple registrations, then register regardless of count
			// In all cases, check if this new registration is replacing an older copy of the SAME quest
			if (!EventType.isMultipleRegistrationAllowed())
			{
				if (_quests[0].getName().equals(q.getName()) || L2NpcTemplate.isAssignableTo(q, _quests[0].getClass()))
					_quests[0] = q;
				else 
					_log.warning("Quest event not allowed in multiple quests. Skipped addition of Event Type \""+EventType+"\" for NPC \""+name+"\" and quest \""+q.getName()+"\".");
			}
			else
			{
				// be ready to add a new quest to a new copy of the list, with larger size than previously.
				Quest[] tmp = new Quest[len+1];
				// loop through the existing quests and copy them to the new list.  While doing so, also 
				// check if this new quest happens to be just a replacement for a previously loaded quest.  
				// If so, just save the updated reference and do NOT use the new list. Else, add the new
				// quest to the end of the new list
				for (int i = 0; i < len; i++)
				{
					if (_quests[i].getName().equals(q.getName()) || L2NpcTemplate.isAssignableTo(q, _quests[i].getClass()))
					{
						_quests[i] = q;
						return;
					}
					else if (L2NpcTemplate.isAssignableTo(_quests[i], q.getClass()))
						return;
					
					tmp[i] = _quests[i];
				}
				tmp[len] = q;
				_questEvents.put(EventType, tmp);
			}
		}
    }
    
	/**
	 * Checks if obj can be assigned to the Class represented by clazz.<br>
	 * This is true if, and only if, obj is the same class represented by clazz,
	 * or a subclass of it or obj implements the interface represented by clazz.
	 * 
	 * @param obj
	 * @param clazz
	 * @return
	 */
	public static boolean isAssignableTo(Object obj, Class<?> clazz)
	{
		return L2NpcTemplate.isAssignableTo(obj.getClass(), clazz);
	}
	
	public static boolean isAssignableTo(Class<?> sub, Class<?> clazz)
	{
		// if clazz represents an interface
		if (clazz.isInterface())
		{
			// check if obj implements the clazz interface
			Class<?>[] interfaces = sub.getInterfaces();
			for (int i = 0; i < interfaces.length; i++)
			{
				if (clazz.getName().equals(interfaces[i].getName()))
					return true;
			}
		}
		else
		{
			do
			{
				if (sub.getName().equals(clazz.getName()))
					return true;
				
				sub = sub.getSuperclass();
			}
			while (sub != null);
		}
		
		return false;
	}
    
	public Quest[] getEventQuests(Quest.QuestEventType EventType) 
	{
		if (_questEvents == null)
			return null;
		
		return _questEvents.get(EventType);
	}
	
	public void setRace(int raceId)
	{
		switch (raceId)
		{
			case 1:
				race = L2NpcTemplate.Race.UNDEAD;
				break;
			case 2:
				race = L2NpcTemplate.Race.MAGICCREATURE;
				break;
			case 3:
				race = L2NpcTemplate.Race.BEAST;
				break;
			case 4:
				race = L2NpcTemplate.Race.ANIMAL;
				break;
			case 5:
				race = L2NpcTemplate.Race.PLANT;
				break;
			case 6:
				race = L2NpcTemplate.Race.HUMANOID;
				break;
			case 7:
				race = L2NpcTemplate.Race.SPIRIT;
				break;
			case 8:
				race = L2NpcTemplate.Race.ANGEL;
				break;
			case 9:
				race = L2NpcTemplate.Race.DEMON;
				break;
			case 10:
				race = L2NpcTemplate.Race.DRAGON;
				break;
			case 11:
				race = L2NpcTemplate.Race.GIANT;
				break;
			case 12:
				race = L2NpcTemplate.Race.BUG;
				break;
			case 13:
				race = L2NpcTemplate.Race.FAIRIE;
				break;
			case 14:
				race = L2NpcTemplate.Race.HUMAN;
				break;
			case 15:
				race = L2NpcTemplate.Race.ELVE;
				break;
			case 16:
				race = L2NpcTemplate.Race.DARKELVE;
				break;
			case 17:
				race = L2NpcTemplate.Race.ORC;
				break;
			case 18:
				race = L2NpcTemplate.Race.DWARVE;
				break;
			case 19:
				race = L2NpcTemplate.Race.OTHER;
				break;
			case 20:
				race = L2NpcTemplate.Race.NONLIVING;
				break;
			case 21:
				race = L2NpcTemplate.Race.SIEGEWEAPON;
				break;
			case 22:
				race = L2NpcTemplate.Race.DEFENDINGARMY;
				break;
			case 23:
				race = L2NpcTemplate.Race.MERCENARIE;
				break;
			default:
				race = L2NpcTemplate.Race.UNKNOWN;
				break;
		}
	}
	
	public L2NpcTemplate.Race getRace()
	{
		if (race == null)
			race = L2NpcTemplate.Race.UNKNOWN;
		
		return race;
	}
	
	//-----------------------------------------------------------------------
	// Npc AI Data By ShanSoft
	public void setAIData(L2NpcAIData aidata)
	{
		_AIdataStatic = aidata;
	}
	//-----------------------------------------------------------------------
	
	public L2NpcAIData getAIDataStatic()
	{
		return _AIdataStatic;
	}
	
	public void addBuffSkill(L2Skill skill)
	{
		if (_buffSkills == null)
			_buffSkills = new FastList<L2Skill>();
		
		_buffSkills.add(skill);
	}
	
	public void addHealSkill(L2Skill skill)
	{
		if (_healSkills == null)
			_healSkills = new FastList<L2Skill>();
		
		_healSkills.add(skill);
	}
	
	public void addAtkSkill(L2Skill skill)
	{
		if (_atkSkills == null)
			_atkSkills = new FastList<L2Skill>();
		
		_atkSkills.add(skill);
	}
	
	public void addDebuffSkill(L2Skill skill)
	{
		if (_debuffSkills == null)
			_debuffSkills = new FastList<L2Skill>();
		
		_debuffSkills.add(skill);
	}
	
	public void addRootSkill(L2Skill skill)
	{
		if (_rootSkills == null)
			_rootSkills = new FastList<L2Skill>();
		
		_rootSkills.add(skill);
	}
	
	public void addSleepSkill(L2Skill skill)
	{
		if (_sleepSkills == null)
			_sleepSkills = new FastList<L2Skill>();
		
		_sleepSkills.add(skill);
	}
	
	public void addStunSkill(L2Skill skill)
	{
		if (_stunSkills == null)
			_stunSkills = new FastList<L2Skill>();
		
		_stunSkills.add(skill);
	}
	
	public void addParalyzeSkill(L2Skill skill)
	{
		if (_paralyzeSkills == null)
			_paralyzeSkills = new FastList<L2Skill>();
		
		_paralyzeSkills.add(skill);
	}
	
	public void addFossilSkill(L2Skill skill)
	{
		if (_fossilSkills == null)
			_fossilSkills = new FastList<L2Skill>();
		
		_fossilSkills.add(skill);
	}
	
	public void addNegativeSkill(L2Skill skill)
	{
		if (_negativeSkills == null)
			_negativeSkills = new FastList<L2Skill>();
		
		_negativeSkills.add(skill);
	}
	
	public void addImmobilizeSkill(L2Skill skill)
	{
		if (_immobilizeSkills == null)
			_immobilizeSkills = new FastList<L2Skill>();
		
		_immobilizeSkills.add(skill);
	}
	
	public void addDOTSkill(L2Skill skill)
	{
		if (_dotSkills == null)
			_dotSkills = new FastList<L2Skill>();
		
		_dotSkills.add(skill);
	}
	
	public void addUniversalSkill(L2Skill skill)
	{
		if (_universalSkills == null)
			_universalSkills = new FastList<L2Skill>();
		
		_universalSkills.add(skill);
	}
	
	public void addCOTSkill(L2Skill skill)
	{
		if (_cotSkills == null)
			_cotSkills = new FastList<L2Skill>();
		
		_cotSkills.add(skill);
	}
	
	public void addManaHealSkill(L2Skill skill)
	{
		if (_manaSkills == null)
			_manaSkills = new FastList<L2Skill>();
		
		_manaSkills.add(skill);
	}
	
	public void addGeneralSkill(L2Skill skill)
	{
		if (_generalSkills == null)
			_generalSkills = new FastList<L2Skill>();
		
		_generalSkills.add(skill);
	}
	
	public void addRangeSkill(L2Skill skill)
	{
		if (skill.getCastRange() <= 150 && skill.getCastRange() > 0)
		{
			if (_shortRangeSkills == null)
				_shortRangeSkills = new FastList<L2Skill>();
			
			_shortRangeSkills.add(skill);
		}
		else if (skill.getCastRange() > 150)
		{
			if (_longRangeSkills == null)
				_longRangeSkills = new FastList<L2Skill>();
			
			_longRangeSkills.add(skill);
		}
	}
	
	public void addSuicideSkill(L2Skill skill)
	{
		if (_suicideSkills == null)
			_suicideSkills = new FastList<L2Skill>();
		
		_suicideSkills.add(skill);
	}
	
	//--------------------------------------------------------------------
	public boolean hasBuffSkill()
	{
		return _buffSkills != null;
	}
	
	public boolean hasHealSkill()
	{
		return _healSkills != null;
	}
	
	public boolean hasAtkSkill()
	{
		return _atkSkills != null;
	}
	
	public boolean hasDebuffSkill()
	{
		return _debuffSkills != null;
	}
	
	public boolean hasRootSkill()
	{
		return _rootSkills != null;
	}
	
	public boolean hasSleepSkill()
	{
		return _sleepSkills != null;
	}
	
	public boolean hasStunSkill()
	{
		return _stunSkills != null;
	}
	
	public boolean hasParalyzeSkill()
	{
		return _paralyzeSkills != null;
	}
	
	public boolean hasFossilSkill()
	{
		return _fossilSkills != null;
	}
	
	public boolean hasNegativeSkill()
	{
		return _negativeSkills != null;
	}
	
	public boolean hasImmobilizeSkill()
	{
		return _immobilizeSkills != null;
	}
	
	public boolean hasDOTSkill()
	{
		return _dotSkills != null;
	}
	
	public boolean hasUniversalSkill()
	{
		return _universalSkills != null;
	}
	
	public boolean hasCOTSkill()
	{
		return _cotSkills != null;
	}
	
	public boolean hasManaHealSkill()
	{
		return _manaSkills != null;
	}
	
	public boolean hasLongRangeSkill()
	{
		return _longRangeSkills != null;
	}
	
	public boolean hasShortRangeSkill()
	{
		return _shortRangeSkills != null;
	}
	
	public boolean hasSkill()
	{
		return _generalSkills != null;
	}
	
	public boolean hasSuicideSkill()
	{
		return _suicideSkills != null;
	}
	
	public String getName()
	{
		return name;
	}
	
	public boolean isSpecialTree()
	{
		return npcId == L2XmassTreeInstance.SPECIAL_TREE_ID;
	}
	
	public boolean isUndead()
	{
		return (race == Race.UNDEAD);
	}
}